<?php


namespace app\logic;


use app\common\model\TopicLog;
use app\common\model\User;
use think\Exception;

class UserLogic
{
    public function saveOpenid($openId,$platform,$parentOpenid){
        $hasInfo = false; //是否有用户信息存储
        $error = false; //是否更新库正常
        $userId = 0;
        //查询是否已经存在数据库，没有则新增
        $checkInfo = User::where(['openid'=>$openId,'platform'=>$platform])->find();
        if(empty($checkInfo)){
            $fir_distribution = 0;
            $sec_distribution = 0;
            if($parentOpenid){
                //查询分销父级id
                $parentInfo = User::where(['openid'=>$parentOpenid])->find();
                if($parentInfo != null){
                    $fir_distribution = $parentInfo->user_id; //一级分销用户
                    $sec_distribution = $parentInfo->fir_distribution; //二级分销用户
                }
            }

            $user = new User;
            // 过滤post数组中的非数据表字段数据
            $user->allowField(true)->save(['openid'=>$openId,'platform'=>$platform,'create_at'=>date('Y-m-d H:i:s'),
                'fir_distribution'=>$fir_distribution,'sec_distribution'=>$sec_distribution]);
            if(empty($user->user_id)){$error = true;}
            $userId = $user->user_id;
        }else{
            $userId = $checkInfo->user_id;
            if($parentOpenid && empty($checkInfo->fir_distribution)){
                //查询分销父级id
                $parentInfo = User::where(['openid'=>$parentOpenid])->find();
                if($parentInfo != null){
                    $checkInfo->fir_distribution = $parentInfo->user_id;
                    $checkInfo->sec_distribution = $parentInfo->fir_distribution;
                    $checkInfo->save();
                }
            }
        }
        if(!empty($checkInfo['nickname'])){$hasInfo =true;}
        return ['hasInfo'=>$hasInfo,'error'=>$error,'userId'=>$userId];
    }

    /**
     * @param $userId
     * @param $topicId
     * @return bool
     * 用户-测评记录
     */
    public function userPlay($userId,$topicId,$share_type){
        try{
            $log = new TopicLog();
            return $log->allowField(true)->save([
                'user_id'=>$userId,
                'topic_id'=>$topicId,
                'topic_share_type'=>$share_type,
                'created_at'=>time()
            ]);
        }catch (Exception $exception){}

    }

    /**
     * 存储用户信息,在授权的时候更新数据
     * @param $params
     * @return bool
     */
    public function saveUserInfo($params){
        $user = new User();
        $data['avatar_url'] = !empty($params['avatarUrl'])?$params['avatarUrl']:'';
        $data['nickname'] = !empty($params['nickName'])?urlencode($params['nickName']):'';
        $save = $user->allowField(true)->save($data,['openid'=>$params['openid']]);
        return $save;
    }
}